import {
  getCardList,
  removeCard,
  setDefault
} from "../../apis/card";
import {
  changeJoinGroupCard,
  directJoinGroup
} from '../../apis/group'
const app = getApp();

Page({
  data: {
    cardList: []
  },

  onLoad(options) {
    this.setData({
      ...options
    });
  },
  onShow() {
    this.getMyCard();
  },

  onShareAppMessage(e) {
    let {
      index
    } = e.target.dataset;

    if (e.from === 'button') {
      return {
        title: `${this.data.cardList[index].userName}的快名片`,
        path: `/pages/cardPreview/index?type=share&cardId=${this.data.cardList[index].cardId}`,
        imageUrl: this.data.cardList[index].shareImage
      }
    };
  },

  getMyCard() {
    getCardList({
      cardType: 1
    }).then(res => {
      if (res.data.code === 200) {
        let {
          rows
        } = res.data;
        rows.forEach(v => {
          if (!new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
          v.imageList = v.imageList.map(val => {
            if (!new RegExp('^https://').test(val) && !new RegExp('^http://').test(val)) val = app.globalData.url + val;
            return val
          });
        });
        this.setData({
          cardList: rows
        });
        if ((this.data.type === 'createGroup' || this.data.type === 'joinGroup') && rows.length !== 0) {
          let card = rows.find(v => v.isDefault === 1) ? rows.find(v => v.isDefault === 1) : rows[0];
          this.setData({
            cardId: card.cardId
          });
        };
        this.data.cardList.forEach((v, i) => {
          wx.getImageInfo({
            src: v.avatar,
            success: res => {
              let avatar = {
                path: res.path,
                width: res.width,
                height: res.height
              };
              this.canvasShareImage(avatar, v.userName, v.company, v.post ? v.post : '暂无', v.label, i);
            }
          });
        });
      };
    });
  },

  // 生成分享小卡片
  canvasShareImage(avatar, userName, company, post, label, index) {
    let cvs = wx.createCanvasContext(`share${index}`);
    cvs.drawImage('../../images/share_bg.png', 0, 0, 420, 336);
    cvs.save();
    cvs.beginPath();
    cvs.arc(210, 70, 54, 0, Math.PI * 2, false);
    cvs.clip();
    if (avatar.width > avatar.height) {
      cvs.drawImage(avatar.path, (avatar.width - avatar.height) / 2, 0, avatar.height, avatar.height, 156, 16, 108, 108);
    } else if (avatar.width < avatar.height) {
      cvs.drawImage(avatar.path, 0, (avatar.height - avatar.width) / 2, avatar.width, avatar.width, 156, 16, 108, 108);
    } else {
      cvs.drawImage(avatar.path, 156, 16, 108, 108);
    };
    cvs.restore();
    cvs.setFillStyle('#fff');
    cvs.setFontSize(26);
    let nameWidth = cvs.measureText(userName).width;
    cvs.fillText(userName, 210 - nameWidth / 2, 164);

    cvs.setFillStyle('#f7f7f7');
    cvs.setFontSize(20);
    let postWidth = cvs.measureText(`${company} · ${post}`).width;
    cvs.fillText(`${company} · ${post}`, 210 - postWidth / 2, 200);

    if (label.length > 0) {
      cvs.setFillStyle('#fff');
      cvs.setFontSize(22);
      label = label.map(v => {
        return {
          labelName: '#' + v,
          labelWidth: cvs.measureText('#' + v).width
        }
      }).sort((a, b) => b.labelWidth - a.labelWidth);
      let lineWidth = cvs.measureText('　|　').width;
      switch (label.length) {
        case 1:
          cvs.fillText(label[0].labelName, 210 - label[0].labelWidth / 2, 260);
          break;
        case 2:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          break;
        case 3:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName, 210 - (label[2].labelWidth) / 2, 300);
          break;
        case 4:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName + '　|　' + label[3].labelName, 210 - (label[2].labelWidth + label[3].labelWidth + lineWidth) / 2, 300);
          break;
        case 5:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName + '　|　' + label[3].labelName + '　|　' + label[4].labelName, 210 - (label[2].labelWidth + label[3].labelWidth + label[4].labelWidth + lineWidth * 2) / 2, 300);
          break;
        default:
          break;
      };
    };

    cvs.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: `share${index}`,
        destWidth: '420',
        destHeight: '336',
        fileType: 'png',
        success: res => {
          this.setData({
            [`cardList[${index}].shareImage`]: res.tempFilePath
          });
        }
      });
    });
  },

  // 查看名片
  previewCard(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/cardPreview/index?from=myCard&type=preview&cardId=${id}`,
    })
  },
  // 删除名片
  handleDelete(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.showModal({
      title: '删除后不可恢复',
      content: '是否删除',
      success: res => {
        if (res.confirm) {
          removeCard(id).then(res => {
            if (res.data.code === 200) {
              this.getMyCard();
            };
          });
        };
      }
    });
  },
  // 修改名片
  modifyCard(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/editCard/index?type=edit&cardId=${id}`
    });
  },
  // 制作名片
  addCard() {
    wx.navigateTo({
      url: '/pages/makecard/index'
    });
  },

  // 设置默认
  setDefaulf(e) {
    let {
      id
    } = e.currentTarget.dataset;
    setDefault(id).then(res => {
      if (res.data.code === 200) {
        this.getMyCard();
      };
    });
  },

  goQRcode(e) {
    let {
      index
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/qrCode/index?type=card&cardId=${this.data.cardList[index].cardId}`
    });
  },

  // 选择名片
  selectedCard(e) {
    let {
      id,
      index
    } = e.currentTarget.dataset;
    this.data.cardList.forEach((v, i) => {
      if (i === index) {
        v.isDefault = 1;
      } else {
        v.isDefault = 0;
      };
    });
    this.setData({
      cardId: id,
      cardList: this.data.cardList
    });
  },

  create() {
    wx.navigateTo({
      url: '/pages/uploadImages/index'
    });
  },

  confirm() {
    if (this.data.type === 'createGroup') {
      wx.redirectTo({
        url: `/pages/createGroup/index?type=createGroup&cardId=${this.data.cardId}`
      });
    } else if (this.data.type === 'updateGroupCard') {
      changeJoinGroupCard(this.data.groupId, this.data.cardId).then(res => {
        if (res.data.code === 200) {
          wx.navigateBack({
            delta: 1
          });
        };
      });
    } else if (this.data.type === 'joinGroup') {
      if (this.data.checked == 1) {
        directJoinGroup(this.data.groupId, this.data.cardId).then(res => {
          if (res.data.code === 200) {
            wx.navigateBack({
              delta: 1
            });
          };
        });
      } else {
        wx.redirectTo({
          url: `/pages/applyGroup/index?type=${this.data.type}&groupId=${this.data.groupId}&cardId=${this.data.cardId}`
        });
      };
    };
  }
})